/**
 * @desc: 预览重新打印弹窗
 * @author: fj
 */
import React, { useState, useEffect, useRef } from "react";
import { Button, Typography, Alert, Popconfirm, Form, Select, Modal, message, Radio } from "antd";
import CommonModal from "@/components/CommonModal";
import CommonTable from "@/components/CommonTable";
import BtnDeleteModal from "./BtnDeleteModal";
import { setPrinterName, getPrinterName } from "@/utils/authority";
import { checkComponentsIsOpen, getAllPrinter, judgeHasWhichPlatform } from "@/utils/print.jsx";
import { findIndex, isEmpty } from "lodash";
import { queryViewAndPrint, getOrderPrintData, updatePrintTime, updatePrinterName, queryPrintCodeDetail, saveCodePrintTask, getSupplierInfo, getKuaiMaiPrint } from "../../service";
import { renderChannelIcon } from "@/utils/utils.jsx";
import { kuaiXiaoPrintFunc } from "@/utils/print.jsx";
import { useNavigate } from "react-router-dom";
import { printKmUniqcode } from '@/utils/printKm.js';
import styles from "./index.module.less";

const { Paragraph } = Typography;
const { Option } = Select;


const PreviewReprintModal = ({ type, record, handleCancel }) => {
	const [form] = Form.useForm();
	//详情数据
	const [data, setData] = useState([]);
	//需要打印的数据
	const [orderList, setOrderList] = useState([]);
	//批量删除数量
	const [deleteVisible, setDeleteVisible] = useState(false);
	//打印机列表
	const [printerList, setPrinterList] = useState([]);
	//打印成功之后的数据
	const [printerSuccessData, setPrinterSuccessData] = useState({});

	//剔除退货数据:returnStatus == 2
	const [formatType, setFormatType] = useState('1');

	const [open, setOpen] = useState(false);

	//是否正在打印唯一码
	const [isPrint, setIsPrint] = useState(false);

	//档口地址信息
	const [shopAddress, setShopAddress] = useState({});

	const navigate = useNavigate();

	//是否是唯一码打印
	const isUnqcode = record.printType == 1 ? true : false;

	const title = isUnqcode ? '唯一码' : '订单';

	const columns = [
		{
			title: "序号",
			dataIndex: "no",
			key: "no",
			width: 60,
		},
		{
			title: "系统订单号",
			dataIndex: "omsOrderSn",
			key: "omsOrderSn",
			width: 180,
			render: (text, record) => {
				return (
					<div>
						<Paragraph style={{ margin: 0 }} copyable={{ text: text }}>
							<span onClick={() => goStorageorder(text)} className="opera-span-common" style={{ cursor: "pointer" }}>
								{text}
							</span>
						</Paragraph>
						<div>{record.createTime}</div>
					</div>
				);
			}
		},
		{
			title: "出库单号",
			dataIndex: "orderSn",
			key: "orderSn",
			width: 160,
			render: (text, record) => {
				return (
					<div>
						<Paragraph>
							<span onClick={() => goOutboundorder(text)} className="opera-span-common" style={{ cursor: "pointer" }}>
								{text}
							</span>
						</Paragraph>
					</div>
				);
			}
		},
		{
			title: "快递",
			dataIndex: "logisticsNo",
			key: "logisticsNo",
			width: 150,
			render: (text, record) => {
				return (
					<div>
						<Paragraph style={{ margin: 0 }} copyable>
							{text}
						</Paragraph>
						<div>
							{record.logisticsCompany}
							{renderChannelIcon(record.logisticsUuid, record.uuid)}
						</div>
					</div>
				);
			}
		},
		{
			title: "收货信息",
			dataIndex: "orderReceiverInfo",
			key: "orderReceiverInfo",
			width: 200
		},
		{
			title: "操作",
			dataIndex: "endTime",
			key: "endTime",
			width: 80,
			render: (text, record, index) => {
				return (
					<span className="opera-span-common">
						<Popconfirm title="确定删除?" onConfirm={() => handleDeleteGoods(index)} okText="确定" cancelText="取消">
							<span>删除</span>
						</Popconfirm>
					</span>
				);
			}
		}
	];

	const codeColumns = [
		{
			title: "序号",
			dataIndex: "no",
			key: "no",
			width: 80
		},
		{
			title: "出库单号",
			dataIndex: "outboundNo",
			key: "outboundNo",
			width: 220,
			render: (text, record) => {
				return (
					<div>
						<Paragraph style={{ margin: 0 }} copyable={{ text: text }}>
							<span onClick={() => goStorageorder(text)} className="opera-span-common" style={{ cursor: "pointer" }}>
								{text}
							</span>
						</Paragraph>
						<div>{record.createTime}</div>
					</div>
				);
			}
		},
		{
			title: "商品唯一码",
			dataIndex: "code",
			key: "code",
			width: 150,
		},
		{
			title: type == 5 ? '退货状态' : "拿货状态",
			dataIndex: type == '5' ? 'returnStatusName' : "statusName",
			key: "statusName",
			width: 100,
		},
		{
			title: "操作",
			dataIndex: "endTime",
			key: "endTime",
			width: 80,
			render: (text, record, index) => {
				return (
					<span className="opera-span-common">
						<Popconfirm title="确定删除?" onConfirm={() => handleDeleteGoods(index)} okText="确定" cancelText="取消">
							<span>删除</span>
						</Popconfirm>
					</span>
				);
			}
		}
	];


	useEffect(() => {
		setOpen(true);
		getPrintRecords();
		getAllPrinter(value => setPrinterList(value));
		const printname = getPrinterName();
		if (printname) {
			form.setFieldsValue({
				printer: printname
			});
		}
	}, [])


	//跳转系统订单
	const goStorageorder = val => {
		navigate("/views/order/list", { state: { orderSn: val } });
	};

	//跳转销售出库单
	const goOutboundorder = val => {
		navigate("/views/StockManage/Outbound", { state: { orderSn: val } });
	};

	//获取打印记录
	const getPrintRecords = async () => {
		START_LOADING();
		const queryApi = isUnqcode ? queryPrintCodeDetail : queryViewAndPrint;
		const { data = [], success } = await queryApi({
			taskId: record.id
		});
		if (success) {
			const arr = data.map(v => v.supplierId);
			const res = await getSupplierInfo(arr);
			if (res.data?.length) {
				const params = {};
				res.data.map(item => {
					if (!params[item.shopName]) {
						params[item.shopName] = item.shopAddress;
					}
				});
				setShopAddress(params);
			}
			setData(data);
		}
		END_LOADING();
	};

	//删除订单
	const handleDeleteGoods = index => {
		const arr = [...data];
		arr.splice(index, 1);
		setData(arr);
	};

	//批量删除订单
	const handleBtnDelete = val => {
		const arr = [...data];
		if (val.start <= val.end) {
			//先要保证尾序号大于首序号
			if (val.reversal && val.reversal[0] == "true") {
				//勾选了反转
				const firstIndex = arr[0] && arr[0].no,
					lastIndex = arr[arr.length - 1] && arr[arr.length - 1].no,
					newData = [];
				for (let i = Number(firstIndex); i <= Number(lastIndex); i++) {
					if (i < Number(val.start) || i > Number(val.end)) {
						newData.push(i);
					}
				}
				newData.map(item => {
					const index = findIndex(arr, ["no", item]);
					if (index > -1) {
						arr.splice(index, 1);
					}
				});
			} else {
				for (let i = Number(val.start); i <= Number(val.end); i++) {
					const index = findIndex(arr, ["no", i]);
					if (index > -1) {
						arr.splice(index, 1);
					}
				}
			}
			setData(arr);
			setDeleteVisible(false);
		} else {
			message.warning("首序号需要小于尾序号");
		}
	};

	//批量删除
	const btnDeleteProps = {
		visible: deleteVisible,
		handleCancel() {
			setDeleteVisible(false);
		},
		handleOk(val) {
			handleBtnDelete(val);
		}
	};

	// 设置打印机名称
	const handlePrinterName = name => {
		setPrinterName(name);
	};

	// 设置打印机名称
	const setPrinterNameConfig = async id => {
		setPrinterSuccessData({});
		const { success, data = {} } = await updatePrinterName([
			{
				printerName: getPrinterName(),
				taskId: id
			}
		]);
		if (success) {
			setPrinterSuccessData(data);
		}
	};

	//取消
	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		handleCancel(printerSuccessData);
	}

	//点击打印
	const onOk = () => {
		form
			.validateFields()
			.then(() => {
				if (data.length > 0) {
					if (isUnqcode) {
						handlePrintUnqCode();
					} else {
						handleOk();
					}
				} else {
					message.info("无订单数据，无法打印");
				}
			})
			.catch(err => {
				console.log(err);
			});
	};

	//打印提交
	const handleOk = async () => {
		START_LOADING();
		const omsOrderSns = [];
		data.map(item => omsOrderSns.push(item.omsOrderSn));
		const res = await getOrderPrintData({
			systemNos: omsOrderSns,
			printPageType: type
		});
		if (res.success && res.data?.length) {
			const arr = [];
			res.data.forEach(item => {
				if (item.items && item.items.length) {
					item.items.forEach(z => {
						if (z.printLogisticsList) {
							z.printLogisticsList.forEach(y => {
								arr.push({
									...y,
									printTaskId: z.printTaskId
								});
							});
						}
					});
				}
			});
			setOrderList(arr);
			// setOrderList(res.data[0].items[0].printLogisticsList);

			setPrinterNameConfig(res.data[0].items[0].printTaskId);
		}
	};

	useEffect(() => {
		if (orderList.length > 0) {
			checkComponentsIsOpen(judgeHasWhichPlatform(orderList), res => {
				if (res.status) {
					handleSubmit();
				}
				END_LOADING();
			});
		}
	}, [orderList]);


	//提交打印操作
	const handleSubmit = () => {
		handleReduceSubmit(0);
	};

	//打印唯一码
	const handlePrintUnqCode = () => {
		const arr = formatType == 1 ? data.filter(v => v.returnStatus != 2) : data;
		const printName = getPrinterName();
		handlePrintKmUnqcode(arr, printName);
	}

	//打印快销唯一码
	const handlePrintKmUnqcode = async (val, printName) => {
		if (isPrint) {
			return message.info('打印作业正在进行中，请勿重复提交');
		}
		START_LOADING();
		const labelTypeMap = {
			'3': 1,
			'4': 3,
			'5': 6
		}
		const { success, data } = await getKuaiMaiPrint({
			codes: val.map(v => v.code),
			labelType: labelTypeMap[type]
		})
		END_LOADING()
		if (success) {
			const arr = JSON.parse(data);
			if(!arr.length > 0) {
				return message.warning('没有可打印的数据');
			}
			setIsPrint(true);
			message.success(`即将打印${val.length}个条码，请等待`);
			printKmUniqcode(arr, printName, () => {
				savePrintRecord(val, printName);
				setIsPrint(false);
			});
		}
	}

	//保存打印记录
	const savePrintRecord = (value, printname) => {
		const arr = [];
		value.map(v => {
			arr.push({
				"outboundNo": v.outboundNo,
				"uniqueCode": v.code
			})
		})
		saveCodePrintTask({
			printerName: printname,
			printPageType: type,
			codePrintSaveVOList: arr
		})
	}

	//打印的数量
	let len = orderList.length;

	//打印面单
	const handleReduceSubmit = num => {
		if (!isEmpty(orderList)) {
			const promise = new Promise(async resolve => {
				const list = orderList[num];
				if (len == 0 || isEmpty(list)) {
					resolve(len);
					return;
				}
				kuaiXiaoPrintFunc({ ...orderList[num], printer: getPrinterName() }, async res => {
					const { status, logPage, printTaskId, orderSn } = res;
					if (status) {
						await updatePrintTime({
							logPage,
							printTaskId,
							systemNos: [orderSn]
						});
						if (len !== 0) {
							len = len - 1;
						}
					}
					handleReduceSubmit(num + 1);
				});
			});
			promise.then(len => {
				Modal.success({
					content: `成功打印${orderList.length - len}条,失败${len}条`
				});
			});
		}
	};

	//表格属性
	const TableProps = {
		data,
		columns: isUnqcode ? codeColumns : columns,
		size: "small",
		// rowKey: "no",
		scroll: { x: 540, y: 300 }
	};

	//打印机options
	const options =
		!isEmpty(printerList) &&
		printerList.map(d => (
			<Option key={d} value={d}>
				{d}
			</Option>
		));

	return (
		<CommonModal
			title="预览并重新打印"
			visible={open}
			afterClose={afterClose}
			onOk={onOk}
			onCancel={onCancel}
			okText="重新打印"
			width={900}
		>
			<div>
				<Alert
					showIcon
					message={
						isUnqcode ?
							<div>①需要手动选择是否剔除掉已经拿货的唯一码信息</div>
							:
							<div>
								①.已剔除上个批次这些仓库订单号里，已作废、异常或运单号获取失败的订单号
								<br />
								②.部分仓库订单号可能修改了快递，会显示当前最新的快递、运单号、收货信息
							</div>
					}
				/>
				<div style={{ display: 'flex', alignItems: 'center' }}>
					<Button onClick={() => setDeleteVisible(true)} style={{ margin: '16px 0' }}>
						批量删除{title}数量
					</Button>
					{isUnqcode && <div style={{ marginLeft: '32px', color: '#000' }}>
						是否剔除退货成功数据：
						<Radio.Group value={formatType} onChange={e => setFormatType(e.target.value)}>
							<Radio value="1">剔除</Radio>
							<Radio value="2">不剔除</Radio>
						</Radio.Group>
					</div>}
				</div>
				<CommonTable {...TableProps} />
				<div className={styles.footer}>
					<span>{title}数量：</span>
					<span className="common-color9">{data.length}</span>
				</div>
				<Form form={form} name="re-print" className="new-search-form-style" style={{ marginBottom: "16px" }}>
					<Form.Item name="printer" rules={[{ required: true, message: "未选择打印机!" }]}>
						<Select
							style={{ width: "210px" }}
							placeholder={
								<>
									<span className="common-color9">*</span>请选择打印机
								</>
							}
							onChange={handlePrinterName}
						>
							{options}
						</Select>
					</Form.Item>
				</Form>
				{deleteVisible && <BtnDeleteModal {...btnDeleteProps} />}
			</div>
		</CommonModal>
	);
};

export default PreviewReprintModal;
